import os
from config import ini_op
from service.sjxz import zddr_upload


def run(llq, zj, hszz, hszb):
  kjnd, km1, km2, folderpath = ini_op.getinivalue('kmyeb_config', 'kjnd', 'km1', 'km2', 'folderpath')
  ksrq = kjnd+'0101'
  jsrq = kjnd+'1231'
  os.makedirs(folderpath, exist_ok=True)
  browser, context, page = llq
  page.click('#toolbar_header_function')
  page.fill('#search', '科目余额表')
  page.wait_for_timeout(2000)
  try:
      page.wait_for_selector('ul.search--result-list', timeout=2000)
  except Exception:
      page.click('.header--search')
  page.locator('ul.search--result-list li').first.click()

  page.locator('[formcontrolname="fiSets_Name"] input').fill(zj)
  page.locator('[formcontrolname="fiSets_Name"] input').press('Enter')
  page.wait_for_timeout(500)

  page.locator('[formcontrolname="accOrg_Name"] input').fill(hszz)
  page.locator('[formcontrolname="accOrg_Name"] input').press('Enter')
  page.wait_for_timeout(500)
  
  page.locator('[formcontrolname="ledger_Name"] input').fill(hszb)
  page.locator('[formcontrolname="ledger_Name"] input').press('Enter')
  page.wait_for_timeout(500)

  page.locator('[formcontrolname="dateYearFrom"] input').click()
  page.locator('.table-hover [title="'+ksrq[:4]+'"]').click()
  page.wait_for_timeout(500)
  
  page.locator('[formcontrolname="dateMonthFrom"] input').click()
  page.locator('.table-hover [title="'+ksrq[4:6]+'"]').click()
  page.wait_for_timeout(500)

  page.locator('[formcontrolname="dateYearTo"] input').click()
  page.locator('.table-hover [title="'+jsrq[:4]+'"]').click()
  page.wait_for_timeout(500)

  page.locator('[formcontrolname="dateMonthTo"] input').click()
  page.locator('.table-hover [title="'+jsrq[4:6]+'"]').click()
  page.wait_for_timeout(500)

  page.locator('#form_from_accTitle input').fill(km1)
  page.locator('#form_from_accTitle input').press('Enter')
  page.wait_for_timeout(500)

  page.locator('#form_to_accTitle input').fill(km2)
  page.locator('#form_to_accTitle input').press('Enter')
  page.wait_for_timeout(500)

  # is_checked = page.locator('#form_detail_accTitle').is_checked()
  # if not is_checked:
  #   page.locator('[for="form_detail_accTitle"]').click()
     
  is_checked = page.locator('#inclNotAccount_f377d355_a944_4990_8c52_96bdc11c788d_in83').is_checked()
  if not is_checked:
    page.locator('[for="inclNotAccount_f377d355_a944_4990_8c52_96bdc11c788d_in83"]').click()
  
  page.click('#button-queryok')

  with page.expect_download(timeout=600000) as download_info:
    page.click('#dropdownMenuButtonExport')
    page.wait_for_timeout(1000)
    page.locator('.dropdown-menu a.ng-star-inserted').last.click()
    download = download_info.value
    filepath = os.path.join(folderpath, hszb+km1+'-'+km2+','+ksrq+'-'+jsrq+'科目余额表导出'+download.suggested_filename[-5:])
    download.save_as(filepath)

  zddr_upload.file_uploads(filepath)
  page.click('[title="科目余额表"] div.nav-link-close')


